import './../sass/header.scss';
import './../sass/testpaper.scss';
import './../font/iconfont.css';

import './../js/testpaperinfo.js'
import './../js/auth.js';

const $ = require('jquery');

const info = location.search.replace('?', '').split("&");
const testId = info[0].split("=")[1];
const testStatus = info[1].split("=")[1];
const token = localStorage.token;
let timer;
$.ajax({
    url: '/tests/getOneTests',
    data: {
        id: testId
    },
    type: 'post',
    success({ code, message, result }) {
        if (code == '1') {
            $(".testtitle").text(result.title)
            $("#totalQuestions").text(result.exercisesId.length);
            $("#answered").text(0);
            $("#unanswered").text(result.exercisesId.length);
            $("#confirm").attr("data-testId", result._id)

            const testPage = result.exercisesId.map((item, index) =>
                `<div>${index + 1}</div>`
            )
            $(".questions").html(testPage);
            function answer(answer) {
                switch (answer) {
                    case '0':
                        return 'A';
                    case '1':
                        return 'B';
                    case '2':
                        return 'C';
                    case '3':
                        return 'D';

                    default:
                        break;
                }
            }
            const test = result.exercisesId.map((paper, index) =>
                ` <li class="item">
                    <div>
                        <p class="questiontype">单选题</p>
                        <p>第${index + 1}题/共${result.exercisesId.length}题</p>
                    </div>
                    <div>
                        <p data-exercisesId="${paper._id}">${paper.topics}</p>
                        <ul class="options">
                            <li>
                                <i>A</i>
                                ${paper.options[0]}
                            </li>
                            <li>
                                <i>B</i>
                                ${paper.options[1]}
                            </li>
                            <li>
                                <i>C</i>
                                ${paper.options[2]}
                            </li>
                            <li>
                                <i>D</i>
                                ${paper.options[3]}
                            </li>
                        </ul>
                        <div>
                            <button class="next" data-answer="${paper.answer}" data-score="${paper.score}">下一题</button>
                        </div>
                    </div>
                    <aside class="collection_resolution" style="display: none">
                        <p>正确答案: <span>${answer(paper.answer)}</span></p>
                        <p>${paper.analysis}</p>
                    </aside>
                </li>`)
            $("#practise ul").html(test);
            if (testStatus == 'tested') {
                $("#practise ul li .collection_resolution").css("display", "block")
                $(".submit").css('display', 'none')
                $("#testType").css("display", "none")
                $("#weidaTile").css("display", "none")
            } else {
                time();
            }
            rotation();
        }
    }
})

// 返回
$("#back").on('click', function () {
    history.go(-1);
})

// 下一题
let score = 0;
function rotation() {
    const tests = $("#practise > ul > li button");
    options();
    [...tests].forEach((item, index) => {
        $(item).on('click', function () {
            const selects = $(item).parent().prev().find('li');
            [...selects].forEach((select, i) => {
                if ($(select).attr('class') == 'select') {
                    $(".questions div").eq(index).addClass('complete');
                    if ($(item).attr('data-answer') == i) {
                        score += Number($(item).attr('data-score'));
                    } else {
                        score = score;
                        if (testStatus == "testing") {
                            $.ajax({
                                url: '/errors/createErrors',
                                data: {
                                    errorAnswer: i,
                                    exerciseId: $(item).parent().prev().prev().attr("data-exercisesid"),
                                    studentId: $("#user").attr("data-studentid")
                                },
                                type: 'post',
                                success(data) {
                                    // console.log(data);
                                }
                            })
                        }
                    }
                }
                if (index + 1 != tests.length) {
                    $(this).parents('ul').css('left', `-${(index + 1) * 600}px`)
                } else {
                    if (testStatus == "testing") {
                        $("#submit_model").fadeIn();
                    }
                }
            })
            $("#answered").text(index + 1);
            $("#unanswered").text(tests.length - (index + 1));
            $("#weida").text(tests.length - (index + 1));
        })
    });
}

function options() {
    $("#practise").on('click', 'li', function () {
        $(this).siblings().removeClass('select');
        $(this).addClass('select');
    })
}

// 剩余时间
function time() {
    let timeTotal = 30;
    let minute = timeTotal;
    let seconds = minute * 60;
    timer = setInterval(() => {
        seconds--
        $("#surplusTime").text(`00:${parseInt(seconds / 60)}:${seconds % 60}`);
        if (seconds == 0) {
            clearInterval(timer);
        }
    }, 1000);
}

$(".submit").on('click', function () {
    const options = $("#practise ul .options");
    let answered = 0;
    score = 0;
    [...options].forEach(option => {
        const selects = $(option).find("li");
        [...selects].forEach((select, index) => {
            if ($(select).attr("class") == "select") {
                if ($(option).next().find("button").attr("data-answer") == index) {
                    score += Number($(option).next().find("button").attr("data-score"));
                } else {
                    score = score;
                }
                answered++;
            }
        })
    })
    $("#answered").text(answered);
    $("#unanswered").text(options.length - answered);
    $("#submit_model").fadeIn();
})
$("#submit_model").on('click', 'button', function () {
    $("#submit_model").fadeOut();
})
$("body").on('keyup', function (e) {
    if (e.key == "Escape") {
        $("#submit_model").fadeOut();
    }
})

// 确认交卷
$("#confirm").on('click', function () {
    if (testStatus == "testing") {

        $.ajax({
            url: '/testeds/saveTest',
            data: {
                studentId: $("#user").attr("data-studentId"),
                testId,
                score
            },
            type: 'post',
            success(data) {
                // console.log(data);
            }
        })
    }
    clearInterval(timer);
    location.assign(`./../html/grade.html?testId=${$("#confirm").attr("data-testId")}&score=${score}&time=${$("#surplusTime").text()}`)
})

